package com.wechat.api.rpc;

import com.wechat.api.util.EncoderUtils;
import com.wechat.api.util.XMLParser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 用于微信认证等基础服务接口访问
 */
@RestController
@RequestMapping("/base")
public class BaseRPC {

    private static Logger logger = LoggerFactory.getLogger(BaseRPC.class);

    @Value("${token}")
    private String CUSTOM_TOKEN;


    /**
     * 认证服务器
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
	@RequestMapping(value = "auth", method = RequestMethod.GET)
	public String wxAuth(String signature, String timestamp,
						 String nonce, String echostr){
	    if (authCheck(signature, timestamp, nonce)){
	        logger.info("认证通过");
            return echostr;
        }else{
	        logger.error("认证失败");
	        return "";
        }
	}


    /**
     * 认证检查数据是否合规
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
	private boolean authCheck(String signature, String timestamp,
                              String nonce){
	    logger.info("signature："+signature);
	    System.out.println("signature："+signature);
	    String[] arrs = {CUSTOM_TOKEN,timestamp,nonce};
	    String sortStr = "";
        Arrays.sort(arrs);
        for (String arr : arrs) {
            sortStr += arr;
        }
        String encoderStr = EncoderUtils.SHA1Encoder(sortStr);
        System.out.println("SHA1加密："+encoderStr);
        logger.info("SHA1加密："+encoderStr);
        if (StringUtils.equalsIgnoreCase(signature, encoderStr)){
            return true;
        }
	    return false;
    }

    @RequestMapping(value = "auth", method = RequestMethod.POST)
    public String receiveMsg(HttpServletRequest request){

        XMLParser.dom4jParser(request);
	    return "";
    }

}
